<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简历解析 - AI简历解析系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        /* 导航栏样式 */
        .navbar {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            position: relative;
            z-index: 1000;
        }
        
        /* 下拉菜单样式 */
        .dropdown-menu {
            z-index: 1001;
            position: absolute;
            top: 100%;
            left: 0;
            will-change: transform;
            transform: translate3d(0, 0, 0);
        }
        
        .navbar-brand {
            color: #667eea !important;
            font-weight: 700;
            font-size: 1.5rem;
        }
        
        .nav-link {
            color: #555 !important;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .nav-link:hover {
            color: #667eea !important;
        }
        
        .nav-link.active {
            color: #667eea !important;
            font-weight: 600;
        }
        
        /* 容器样式 */
        .main-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            margin: 0 auto;
        }
        
        /* 文件上传区域 */
        .upload-area {
            border: 2px dashed #e0e0e0;
            border-radius: 15px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }
        
        .upload-area:hover {
            border-color: #667eea;
            background: #f0f4ff;
        }
        
        .upload-area.dragover {
            border-color: #667eea;
            background: #f0f4ff;
        }
        
        /* 表单元素样式 */
        .form-label {
            color: #555;
            font-weight: 500;
            margin-bottom: 8px;
            display: block;
        }
        
        .form-control,
        .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 16px;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .form-control:focus,
        .form-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        /* 按钮样式 */
        .btn-primary,
        #submitBtn {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 10px;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            max-width: 200px;
            margin: 0 auto;
            display: block;
        }
        
        .btn-primary:hover,
        #submitBtn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:active,
        #submitBtn:active {
            transform: translateY(0);
        }
        
        /* 结果区域 */
        .result-section {
            background-color: #f8f9fa;
            border-radius: 15px;
            padding: 30px;
            margin-top: 30px;
        }
        
        /* 信息卡片 */
        .info-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
        }
        
        .info-card:hover {
            box-shadow: 0 8px 25px rgba(0,0,0,0.08);
            transform: translateY(-2px);
        }
        
        .info-card h5 {
            color: #333;
            margin-bottom: 15px;
            font-weight: 600;
        }
        
        /* 技能标签 */
        .skill-tag {
            display: inline-block;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 6px 14px;
            border-radius: 20px;
            margin: 3px;
            font-size: 0.9em;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
        }
        
        /* 聊天区域 */
        .chat-section {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            padding: 25px;
            margin-top: 30px;
        }
        
        #chatMessages {
            height: 400px;
            overflow-y: auto;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            background: #f8f9fa;
            margin-bottom: 20px;
        }
        
        #chatInput {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 16px;
            transition: all 0.3s ease;
            width: calc(100% - 120px);
            display: inline-block;
        }
        
        #chatInput:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        button[onclick="sendMessage()"] {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 10px;
            padding: 12px 20px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100px;
            display: inline-block;
            margin-left: 10px;
        }
        
        button[onclick="sendMessage()"]:hover {
            transform: translateY(-1px);
            box-shadow: 0 3px 10px rgba(102, 126, 234, 0.3);
        }
        
        /* 聊天消息气泡 */
        .text-end.mb-2 .d-inline-block,
        .text-start.mb-2 .d-inline-block {
            border-radius: 18px;
            padding: 12px 18px;
            max-width: 80%;
            position: relative;
        }
        
        .text-end.mb-2 .d-inline-block {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .text-start.mb-2 .d-inline-block {
            background: #f0f0f0;
            color: #333;
        }
        
        /* 标题样式 */
        h1, h3 {
            color: #333;
            font-weight: 700;
            text-align: center;
            margin-bottom: 30px;
        }
        
        /* 错误提示 */
        .alert {
            border-radius: 10px;
            padding: 15px;
            margin-top: 20px;
            border: none;
        }
        
        /* 滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-container {
                padding: 25px;
            }
            
            .navbar {
                margin-bottom: 15px;
            }
            
            #chatInput {
                width: calc(100% - 100px);
            }
            
            button[onclick="sendMessage()"] {
                width: 80px;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg">
        <div class="container">
            <a class="navbar-brand" href="/">AI简历解析系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <div class="navbar-nav ms-auto">
                    <a class="nav-link" href="/">首页</a>
                    <a class="nav-link active" href="/resume">简历解析</a>
                    <div class="nav-item dropdown" id="userDropdown" style="display: none;">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <span id="usernameDisplay">用户</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/">首页</a></li>
                            <li><a class="dropdown-item" href="/resume">简历解析</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="#" onclick="logout()"><i class="fas fa-sign-out-alt mr-2"></i> 退出登录</a></li>
                        </ul>
                    </div>
                    <a class="nav-link" href="/login" id="loginLink" style="display: none;">
                        <i class="fas fa-sign-in-alt"></i> 登录
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container main-container">
        <h1 class="text-center mb-4">简历解析</h1>
        
        <!-- 文件上传区域 -->
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="upload-area" id="uploadArea">
                    <form th:action="@{/parse-resume}" method="post" enctype="multipart/form-data" id="uploadForm">
                        <div class="mb-3">
                            <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                            <h5>选择简历文件</h5>
                            <p class="text-muted">支持 PDF 和 Word 文档格式</p>
                        </div>
                        
                        <div class="mb-3">
                            <label for="aiModel" class="form-label">选择AI解析模型：</label>
                            <select class="form-select" name="aiModel" id="aiModel" required>
                                <option value="deepseek" selected>DeepSeek</option>
                                <option value="hunyuan-lite">腾讯混元大模型</option>
                            </select>
                            <small class="form-text text-muted">
                                DeepSeek：通用性强，解析准确<br>
                                腾讯混元：中文理解更好，适合中文简历
                            </small>
                        </div>
                        
                        <div class="mb-3">
                            <input type="file" class="form-control" name="file" id="fileInput" 
                                   accept=".pdf,.doc,.docx" required>
                        </div>
                        <button type="submit" id="submitBtn">
                            <span id="submitText"><i class="fas fa-file-alt"></i> 开始解析</span>
                            <span id="loadingSpinner" class="spinner-border spinner-border-sm ms-2" style="display: none;"></span>
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- 错误提示 -->
        <div th:if="${error}" class="alert alert-danger mt-3" role="alert">
            <i class="fas fa-exclamation-triangle"></i>
            <span th:text="${error}"></span>
        </div>

        <!-- 解析结果 -->
            <div th:if="${success != null and success == true and resumeData != null}" class="result-section">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h3>解析结果 - <span th:text="${fileName}"></span></h3>
                </div>
            
            <!-- 基本信息 -->
            <div th:if="${resumeData.name != null and resumeData.name != '' or 
                         resumeData.email != null and resumeData.email != '' or 
                         resumeData.phone != null and resumeData.phone != '' or 
                         resumeData.address != null and resumeData.address != '' or 
                         resumeData.age != null and resumeData.age != '' or 
                         resumeData.birthDate != null and resumeData.birthDate != '' or 
                         resumeData.nationality != null and resumeData.nationality != '' or 
                         resumeData.linkedin != null and resumeData.linkedin != '' or 
                         resumeData.github != null and resumeData.github != '' or 
                         resumeData.website != null and resumeData.website != ''}" 
                 class="info-card">
                <h5><i class="fas fa-user text-primary"></i> 基本信息</h5>
                <div class="row">
                    <div class="col-md-6">
                        <p th:if="${resumeData.name != null and resumeData.name != ''}"><strong>姓名：</strong><span th:text="${resumeData.name}"></span></p>
                        <p th:if="${resumeData.email != null and resumeData.email != ''}"><strong>邮箱：</strong><span th:text="${resumeData.email}"></span></p>
                        <p th:if="${resumeData.phone != null and resumeData.phone != ''}"><strong>电话：</strong><span th:text="${resumeData.phone}"></span></p>
                        <p th:if="${resumeData.age != null and resumeData.age != ''}"><strong>年龄：</strong><span th:text="${resumeData.age}"></span></p>
                    </div>
                    <div class="col-md-6">
                        <p th:if="${resumeData.address != null and resumeData.address != ''}"><strong>地址：</strong><span th:text="${resumeData.address}"></span></p>
                        <p th:if="${resumeData.birthDate != null and resumeData.birthDate != ''}"><strong>出生日期：</strong><span th:text="${resumeData.birthDate}"></span></p>
                        <p th:if="${resumeData.nationality != null and resumeData.nationality != ''}"><strong>国籍：</strong><span th:text="${resumeData.nationality}"></span></p>
                        <p th:if="${resumeData.linkedin != null and resumeData.linkedin != ''}"><strong>LinkedIn：</strong><span th:text="${resumeData.linkedin}"></span></p>
                        <p th:if="${resumeData.github != null and resumeData.github != ''}"><strong>GitHub：</strong><span th:text="${resumeData.github}"></span></p>
                        <p th:if="${resumeData.website != null and resumeData.website != ''}"><strong>个人网站：</strong><span th:text="${resumeData.website}"></span></p>
                    </div>
                </div>
            </div>

            <!-- 教育经历 -->
            <div th:if="${not #lists.isEmpty(resumeData.education)}" class="info-card">
                <h5><i class="fas fa-graduation-cap text-primary"></i> 教育经历</h5>
                <div th:each="edu : ${resumeData.education}" th:if="${edu.school != null and edu.school != '' or edu.degree != null and edu.degree != '' or edu.major != null and edu.major != ''}" class="mb-3">
                    <div class="row">
                        <div class="col-md-4">
                            <strong th:if="${edu.school != null and edu.school != ''}" th:text="${edu.school}"></strong>
                            <br th:if="${edu.school != null and edu.school != '' and edu.degree != null and edu.degree != ''}">
                            <span th:if="${edu.degree != null and edu.degree != ''}" th:text="${edu.degree}"></span>
                        </div>
                        <div class="col-md-3">
                            <span th:if="${edu.major != null and edu.major != ''}" th:text="${edu.major}"></span>
                        </div>
                        <div class="col-md-2">
                            <span th:if="${edu.startDate != null and edu.startDate != '' and edu.endDate != null and edu.endDate != ''}" 
                                  th:text="${edu.startDate + ' - ' + edu.endDate}"></span>
                            <br th:if="${(edu.startDate != null and edu.startDate != '' and edu.endDate != null and edu.endDate != '') and (edu.graduationYear != null and edu.graduationYear != '')}">
                            <span th:if="${edu.graduationYear != null and edu.graduationYear != ''}" th:text="${edu.graduationYear}"></span>
                        </div>
                        <div class="col-md-3">
                            <span th:if="${edu.gpa != null and edu.gpa != ''}" th:text="'GPA: ' + ${edu.gpa}"></span>
                            <br th:if="${(edu.gpa != null and edu.gpa != '') and (edu.description != null and edu.description != '')}">
                            <span th:if="${edu.description != null and edu.description != ''}" th:text="${edu.description}"></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 工作经历 -->
            <div th:if="${resumeData.workExperience != null and not #lists.isEmpty(resumeData.workExperience)}" class="info-card">
                <h5><i class="fas fa-briefcase text-primary"></i> 工作经历</h5>
                <div th:each="work : ${resumeData.workExperience}" th:if="${work.company != null and work.company != '' or work.position != null and work.position != ''}" class="mb-3">
                    <div class="row mb-2">
                        <div class="col-md-4">
                            <strong th:if="${work.company != null and work.company != ''}" th:text="${work.company}"></strong>
                            <br th:if="${work.company != null and work.company != '' and work.position != null and work.position != ''}">
                            <span th:if="${work.position != null and work.position != ''}" th:text="${work.position}"></span>
                        </div>
                        <div class="col-md-4">
                            <span th:if="${work.startDate != null and work.startDate != '' and work.endDate != null and work.endDate != ''}" 
                                  th:text="${work.startDate + ' - ' + work.endDate}"></span>
                            <br th:if="${(work.startDate != null and work.startDate != '' and work.endDate != null and work.endDate != '') and (work.location != null and work.location != '')}">
                            <span th:if="${work.location != null and work.location != ''}" th:text="${work.location}"></span>
                            <br th:if="${(work.location != null and work.location != '') and (work.department != null and work.department != '')}">
                            <span th:if="${work.department != null and work.department != ''}" th:text="${work.department}"></span>
                        </div>
                        <div class="col-md-4">
                            <span th:if="${work.description != null and work.description != ''}" th:text="${work.description}"></span>
                        </div>
                    </div>
                    <div th:if="${work.achievements != null and not #lists.isEmpty(work.achievements)}" class="mt-2">
                        <strong th:if="${work.achievements[0] != null and work.achievements[0] != ''}">主要成就：</strong>
                        <ul class="mt-1">
                            <li th:each="achievement : ${work.achievements}" th:if="${achievement != null and achievement != ''}" th:text="${achievement}"></li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- 技能 -->
            <div th:if="${resumeData.skills != null and not #lists.isEmpty(resumeData.skills)}" class="info-card">
                <h5><i class="fas fa-tools text-primary"></i> 技能</h5>
                <div>
                    <span th:each="skill : ${resumeData.skills}" th:if="${skill != null and skill != ''}" class="skill-tag" th:text="${skill}"></span>
                </div>
            </div>

            <!-- 个人总结 -->
            <div th:if="${resumeData.summary != null and resumeData.summary != '' and resumeData.summary != '简历解析失败，请重试'}" class="info-card">
                <h5><i class="fas fa-comment text-primary"></i> 个人总结</h5>
                <p th:text="${resumeData.summary}"></p>
            </div>
            
            <!-- 求职意向 -->
            <div th:if="${resumeData.objective != null and resumeData.objective != ''}" class="info-card">
                <h5><i class="fas fa-target text-primary"></i> 求职意向</h5>
                <p th:text="${resumeData.objective}"></p>
            </div>
            
            <!-- 语言能力 -->
            <div th:if="${resumeData.languages != null and not #lists.isEmpty(resumeData.languages)}" class="info-card">
                <h5><i class="fas fa-language text-primary"></i> 语言能力</h5>
                <div>
                    <span th:each="language : ${resumeData.languages}" th:if="${language != null and language != ''}" class="skill-tag" th:text="${language}"></span>
                </div>
            </div>
            
            <!-- 证书资质 -->
            <div th:if="${resumeData.certifications != null and not #lists.isEmpty(resumeData.certifications)}" class="info-card">
                <h5><i class="fas fa-certificate text-primary"></i> 证书资质</h5>
                <ul>
                    <li th:each="cert : ${resumeData.certifications}" th:if="${cert != null and cert != ''}" th:text="${cert}"></li>
                </ul>
            </div>
            
            <!-- 项目经验 -->
            <div th:if="${resumeData.projects != null and not #lists.isEmpty(resumeData.projects)}" class="info-card">
                <h5><i class="fas fa-project-diagram text-primary"></i> 项目经验</h5>
                <ul>
                    <li th:each="project : ${resumeData.projects}" th:if="${project != null and project != ''}" th:text="${project}"></li>
                </ul>
            </div>

            <!-- 简历质量分析 -->
            <div th:if="${analysis != null and (analysis.overallScore != null and analysis.overallScore != '' and analysis.overallScore != '-') or (analysis.analysisSummary != null and analysis.analysisSummary != '' and not #strings.contains(analysis.analysisSummary, '出现问题'))}" class="info-card">
                <h5><i class="fas fa-chart-line text-primary"></i> 简历质量分析</h5>
                <div class="row">
                    <div class="col-md-6">
                        <p th:if="${analysis.overallScore != null and analysis.overallScore != '' and analysis.overallScore != '-'}">
                            <strong>整体评分：</strong>
                            <span class="badge" th:classappend="${analysis.overallScore == 'A'} ? 'bg-success' : (${analysis.overallScore == 'B'} ? 'bg-info' : (${analysis.overallScore == 'C'} ? 'bg-warning' : 'bg-danger'))"
                                  th:text="${analysis.overallScore}"></span>
                        </p>
                        <p th:if="${analysis.complete != null}">
                            <strong>完整性：</strong>
                            <span th:text="${analysis.complete} ? '完整' : '不完整'"
                                  th:classappend="${analysis.complete} ? 'text-success' : 'text-warning'"></span>
                        </p>
                    </div>
                    <div class="col-md-6" th:if="${analysis.analysisSummary != null and analysis.analysisSummary != ''}">
                        <p><strong>分析总结：</strong></p>
                        <p th:text="${analysis.analysisSummary}"></p>
                    </div>
                </div>
                
                <div th:if="${analysis.missingSections != null and not #lists.isEmpty(analysis.missingSections)}" class="mt-3">
                    <h6><i class="fas fa-exclamation-triangle text-warning"></i> 缺失内容</h6>
                    <ul class="list-unstyled">
                        <li th:each="missing : ${analysis.missingSections}" th:if="${missing != null and missing != '' and missing != '无法自动分析'}" 
                            th:text="${missing}" class="text-warning"></li>
                    </ul>
                </div>
                
                <div th:if="${analysis.gaps != null and not #lists.isEmpty(analysis.gaps)}" class="mt-3">
                    <h6><i class="fas fa-clock text-info"></i> 时间断层</h6>
                    <ul class="list-unstyled">
                        <li th:each="gap : ${analysis.gaps}" th:if="${gap != null and gap != ''}" 
                            th:text="${gap}" class="text-info"></li>
                    </ul>
                </div>
                
                <div th:if="${analysis.suggestions != null and not #lists.isEmpty(analysis.suggestions)}" class="mt-3">
                    <h6><i class="fas fa-lightbulb text-success"></i> 优化建议</h6>
                    <ul>
                        <li th:each="suggestion : ${analysis.suggestions}" th:if="${suggestion != null and suggestion != '' and not #strings.contains(suggestion, '请重试')}" 
                            th:text="${suggestion}" class="text-success"></li>
                    </ul>
                </div>
            </div>

            <!-- 隐藏的JSON数据输入框 -->
            <input type="hidden" id="resumeDataJsonInput" th:value="${resumeDataJson}" />
            <input type="hidden" id="resumeIdInput" th:value="${resumeId}" />

            <!-- 智能Chat界面 -->
            <div th:if="${resumeData != null}" class="info-card">
                <h5><i class="fas fa-comments text-primary"></i> 智能HR助手</h5>
                <div id="chatContainer">
                    <div id="chatMessages" class="mb-3" style="max-height: 300px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 5px; padding: 10px;">
                        <div th:each="msg : ${chatMessages}" 
                             th:classappend="${msg.role == 'user'} ? 'text-end' : 'text-start'"
                             class="mb-2">
                            <div th:classappend="${msg.role == 'user'} ? 'bg-primary text-white' : 'bg-light'"
                                 class="d-inline-block px-3 py-2 rounded" 
                                 style="max-width: 80%;">
                                <span th:text="${msg.content}"></span>
                                <br>
                                <small class="text-muted" th:text="${msg.timestamp}"></small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="input-group">
                        <input type="text" id="chatInput" class="form-control" 
                               placeholder="输入您的问题，例如：这位候选人适合什么职位？"
                               onkeypress="if(event.key === 'Enter') sendMessage()">
                        <button class="btn btn-primary" onclick="sendMessage()">
                            <i class="fas fa-paper-plane"></i> 发送
                        </button>
                    </div>
                </div>
            </div>


        </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://kit.fontawesome.com/a076d05399.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // 全局变量
        let selectedAiModel = 'deepseek'; // 默认使用DeepSeek，会被DOMContentLoaded中设置的值覆盖

        // 检查用户登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            
            // 仅更新导航栏状态，不强制要求登录
            if (token && username) {
                document.getElementById('usernameDisplay').textContent = username;
                document.getElementById('userDropdown').style.display = 'block';
                document.getElementById('loginLink').style.display = 'none';
            } else {
                // 未登录，显示登录链接
                document.getElementById('userDropdown').style.display = 'none';
                document.getElementById('loginLink').style.display = 'block';
            }
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('username');
            localStorage.removeItem('role');
            window.location.href = '/login';
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkLoginStatus();
            
            // 从URL参数获取AI模型
            const urlParams = new URLSearchParams(window.location.search);
            const aiModelFromUrl = urlParams.get('aiModel');
            
            // 从localStorage获取之前选择的模型，或者从URL参数，默认DeepSeek
            const savedModel = localStorage.getItem('selectedAiModel');
            if (aiModelFromUrl) {
                selectedAiModel = aiModelFromUrl;
                localStorage.setItem('selectedAiModel', aiModelFromUrl); // 保存选择
            } else if (savedModel) {
                selectedAiModel = savedModel;
            } else {
                selectedAiModel = 'deepseek';
            }
            
            // 设置选择框的值
            const aiModelSelect = document.getElementById('aiModel');
            if (aiModelSelect) {
                aiModelSelect.value = selectedAiModel;
            }
            
            console.log('当前AI模型:', selectedAiModel);
            
            // 监听模型选择变化
            if (aiModelSelect) {
                aiModelSelect.addEventListener('change', function() {
                    selectedAiModel = this.value;
                    localStorage.setItem('selectedAiModel', selectedAiModel);
                    console.log('AI模型已切换为:', selectedAiModel);
                    
                    // 更新URL参数，不刷新页面
                    const url = new URL(window.location);
                    url.searchParams.set('aiModel', selectedAiModel);
                    window.history.replaceState({}, '', url);
                });
            }
            
            // 获取简历JSON数据
            const jsonInput = document.getElementById('resumeDataJsonInput');
            if (jsonInput && jsonInput.value && jsonInput.value.trim()) {
                try {
                    // 直接使用字符串，不需要解析为对象
                    resumeDataJson = jsonInput.value.trim();
                    console.log('成功获取简历JSON数据');
                    console.log('使用AI模型:', selectedAiModel);
                } catch (e) {
                    console.error('解析JSON数据失败:', e);
                    resumeDataJson = null;
                }
            } else {
                console.warn('未找到简历JSON数据');
            }
        });
    </script>
<script>
    // 文件拖拽上传
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    const submitBtn = document.getElementById('submitBtn');
    const submitText = document.getElementById('submitText');
    const loadingSpinner = document.getElementById('loadingSpinner');

    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            fileInput.files = files;
        }
    });

    // 表单提交处理
    document.getElementById('uploadForm').addEventListener('submit', function() {
        submitBtn.disabled = true;
        submitText.textContent = '解析中...';
        loadingSpinner.style.display = 'inline-block';
    });

    // 文件选择后显示文件名
    fileInput.addEventListener('change', function() {
        if (this.files.length > 0) {
            const fileName = this.files[0].name;
            uploadArea.querySelector('h5').textContent = `已选择: ${fileName}`;
        }
    });

    // Chat功能
    let chatHistory = [];
    
    // 从隐藏的输入框获取JSON数据
    let resumeDataJson = null;
    
    // 在页面加载后获取JSON数据
    document.addEventListener('DOMContentLoaded', function() {
        const jsonInput = document.getElementById('resumeDataJsonInput');
        if (jsonInput && jsonInput.value && jsonInput.value.trim()) {
            resumeDataJson = jsonInput.value.trim();
            console.log('成功获取简历JSON数据用于聊天');
        } else {
            console.warn('未找到简历JSON数据');
        }
    });

    function sendMessage() {
        console.log('sendMessage被调用');
        const input = document.getElementById('chatInput');
        if (!input) {
            console.error('找不到chatInput元素');
            return;
        }
        
        const message = input.value.trim();
        console.log('消息内容:', message);
        
        if (!message) {
            console.log('消息为空，不发送');
            return;
        }
        
        if (!resumeDataJson) {
            console.error('简历数据异常');
            addMessageToChat('assistant', '⚠️ 系统检测到简历数据异常，请重新上传简历文件。');
            return;
        }
        
        // 获取当前选择的AI模型
        const aiModelSelect = document.getElementById('aiModel');
        const currentModel = aiModelSelect ? aiModelSelect.value : 'deepseek';
        console.log('正在发送消息，模型:', currentModel);
        
        // 添加用户消息到界面
        addMessageToChat('user', message);
        input.value = '';
        
        // 发送请求前先添加用户消息到历史
            const userMessage = {
                role: 'user',
                content: message,
                timestamp: new Date().toString()
            };
            chatHistory.push(userMessage);
            
            // 禁用输入和发送按钮
            input.disabled = true;
            const sendBtn = document.querySelector('button[onclick="sendMessage()"]');
            if (sendBtn) sendBtn.disabled = true;
            
            // 发送请求
            $.ajax({
                url: '/chat',
                method: 'POST',
                data: {
                    question: message,
                    resumeDataJson: resumeDataJson,
                    chatHistory: JSON.stringify(chatHistory),
                    aiModel: currentModel
                },
                success: function(response) {
                    console.log('收到回复:', response);
                    
                    // 更新聊天历史
                    chatHistory = response.messages || [];
                    
                    // 添加AI回复到聊天界面
                    addMessageToChat('assistant', response.answer);
                    
                    // 重新启用输入和发送按钮
                    input.disabled = false;
                    if (sendBtn) sendBtn.disabled = false;
                },
                error: function(xhr, status, error) {
                    console.error('发送失败:', status, error);
                    addMessageToChat('assistant', '❌ 抱歉，发送消息失败，请稍后重试。');
                    
                    // 重新启用输入和发送按钮
                    input.disabled = false;
                    if (sendBtn) sendBtn.disabled = false;
                    
                    // 移除失败的用户消息
                    chatHistory.pop();
                }
            });
    }

    function addMessageToChat(role, content) {
        const messagesContainer = document.getElementById('chatMessages');
        if (!messagesContainer) {
            console.error('找不到chatMessages元素');
            return;
        }
        
        const messageDiv = document.createElement('div');
        messageDiv.className = role === 'user' ? 'text-end mb-2' : 'text-start mb-2';
        
        const bubbleDiv = document.createElement('div');
        bubbleDiv.className = role === 'user' 
            ? 'd-inline-block px-3 py-2 rounded bg-primary text-white' 
            : 'd-inline-block px-3 py-2 rounded bg-light';
        bubbleDiv.style.maxWidth = '80%';
        
        // 设置内容并转义HTML
        bubbleDiv.textContent = content;
        
        // 添加时间戳
        const timeSpan = document.createElement('small');
        timeSpan.className = 'text-muted d-block mt-1';
        timeSpan.textContent = new Date().toLocaleString();
        bubbleDiv.appendChild(document.createElement('br'));
        bubbleDiv.appendChild(timeSpan);
        
        messageDiv.appendChild(bubbleDiv);
        messagesContainer.appendChild(messageDiv);
        
        // 滚动到底部
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // 支持回车发送
    document.getElementById('chatInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            console.log('按下了Enter键');
            sendMessage();
        }
    });
    
    // 检查聊天功能是否初始化完成
    document.addEventListener('DOMContentLoaded', function() {
        const chatInput = document.getElementById('chatInput');
        const chatMessages = document.getElementById('chatMessages');
        if (chatInput && chatMessages) {
            console.log('聊天功能已初始化完成');
        } else {
            console.error('聊天功能初始化失败，缺少必要元素');
        }
    });


</script>
</body>
</html>
